<template>
<div>
  <el-row>
    <el-col>
    <div class="condition">
      <div>
        按企业名称查询   <el-select v-model="companyOption"   placeholder="请选择">
          <el-option
            v-for="item in tempDataTable"
            :key="item.company"
            :label="item.company"
            :value="item.company">
          </el-option>
        </el-select>
      </div>
      <el-button type = "primary" size="small" style="margin-left:1rem" @click="filterWithCompany">查询</el-button>
      <el-button type = "primary" size="small" @click="clearData()">取消</el-button>
      <el-button type = "primary" size="small" @click="clearData()">清空</el-button>
    </div>
    <div style="text-align:left;margin-top:1rem;margin-bottom:1rem">
        <el-button type = "primary" @click="addData()"  size="small">添加</el-button>
        <el-button type = "primary" @click="delData()"  size="small">删除</el-button>
        <el-button type = "primary" @click="saveData()"  size="small">保存</el-button>
        <el-button type = "primary" @click="cancelBtn()"  size="small">取消</el-button>
      </div>
    <el-table size="mini" ref="multipleTable" :data="view_info.tabledata" border style="width: 100%" highlight-current-row>
      <!-- <el-table-column type="index"></el-table-column> -->
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column v-for="(v,i) in view_info.columns"  :key='i' :prop="v.field" :label="v.title" :width="v.width" :show-overflow-tooltip="true">
          <template slot-scope="scope" >
            <div @dblclick="tabledbclink(scope.row)">
              <span v-if="scope.row.isSet">
                <div v-if="v.type === 'date'">
                  <el-date-picker v-model="view_info.sel[v.field]" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </div>
                <div v-else>
                  <el-input size="small" placeholder="请输入内容" v-model="view_info.sel[v.field]">
                  </el-input>
                </div>
              </span>
              <span v-else>{{scope.row[v.field]}}</span>
            </div>
          </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
          <template slot-scope="scope">
              <span class="el-tag el-tag--info el-tag--mini" style="cursor: pointer;" @click="changeTableData(scope.row)">
                  {{scope.row.isSet?'保存':"修改"}}
              </span>
              <span v-if="!scope.row.isSet" class="el-tag el-tag--danger el-tag--mini" style="cursor: pointer;"  @click="delTableData(scope.row)">
                  删除
              </span>
              <span v-else class="el-tag  el-tag--mini" style="cursor: pointer;" @click="cancelTableData(scope.row)">
                  取消
              </span>
          </template>
      </el-table-column>
  </el-table>
  </el-col>
      <el-col>
          <div class="el-table-add-row" style="width: 99.2%;" @click="addTableData()" v-show='false'><span>+ 添加</span></div>
      </el-col>
  </el-row>
</div>
</template>
<script>
export default {
  data () {
    return {
      view_info: {
        sel: null, // 选中行
        editID: 0,
        columns: [
          { field: 'company', title: '企业名称', width: 120, type: 'text' },
          { field: 'name', title: '实用新型号', width: 120, type: 'text' },
          { field: 'phone', title: '实用新型', width: 120, type: 'text' },
          { field: 'address', title: '发明专利号', width: 120, type: 'text' },
          { field: 'zhuanli', title: '发明专利', width: 120, type: 'text' },
          { field: 'count', title: '专利数量', width: 120, type: 'text' }],
        tabledata: []
      },
      companyOption: '',
      companyOptions: [],
      nameOption: '',
      tempDataTable: []
    }
  },
  methods: {
    addTableData () {
      for (let i of this.view_info.tabledata) {
        if (i.isSet) return this.$message.warning('请先保存当前编辑项')
      }
      let j = { id: 0, 'company': '', 'name': '', 'phone': '', 'address': '', 'zhuanli': '', 'count': '', 'isSet': true }
      this.view_info.tabledata.push(j)
      this.view_info.sel = JSON.parse(JSON.stringify(j))
    },
    clearTableState () {
      this.view_info.editID = 0
      this.view_info.sel = null
    },
    cancelTableData (row) {
      console.log(row.isSet)
      row.isSet = !row.isSet
      this.clearTableState()
    },
    tabledbclink (row) {
      console.log(row)
      if (this.view_info.editID > 0) {
        this.$message.warning('请先保存当前修改')
        return
      }
      if (row.isSet === false) {
        this.view_info.sel = JSON.parse(JSON.stringify(row))
        row.isSet = true
        this.view_info.editID = row.id
      }
    },
    addData () {
      this.addTableData()
    },
    delData () {
      var selectRows = this.$refs.multipleTable.store.states.selection
      selectRows.forEach(row => {
        this.delTableData(row)
      })
    },
    saveData () {
      for (let i of this.view_info.tabledata) {
        if (i.id === 0) {
          this.changeTableData(i)
        }
      }
    },
    cancelBtn () {
      if (this.view_info.editID > 0) {
        for (let i of this.view_info.tabledata) {
          if (i.id === this.view_info.editID) {
            this.cancelTableData(i)
          }
        }
      }
      console.log(this.$refs.multipleTable)
    },
    changeTableData (row) {
      if (this.view_info.editID > 0) {
        if (this.view_info.editID !== row.id) {
          this.$message.warning('请先保存当前修改')
          return
        }
        console.log('update data ' + this.view_info.editID)
        const SQL = `update zhuanli set company='${this.view_info.sel.company}',
        name='${this.view_info.sel.name}'
        phone='${this.view_info.sel.phone}' 
        address='${this.view_info.sel.address}'
        zhuanli='${this.view_info.sel.zhuanli}'
        count='${this.view_info.sel.count}'`
        console.log(SQL)
        this.$db.run(SQL, err => {
          if (err) {
            this.$message.warning('保存失败 er：' + err)
          } else {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.clearTableState()
            this.getSelfTableData()
          }
        })
        return
      }
      // 提交数据
      if (row.isSet) {
        console.log(this.view_info.sel)
        const SQL = `INSERT INTO zhuanli (company,name,phone,address,zhuanli,count)
        VALUES ('${this.view_info.sel.company}','${this.view_info.sel.name}','${this.view_info.sel.phone}','${this.view_info.sel.address}','${this.view_info.sel.zhuanli}','${this.view_info.sel.count}')`
        console.log(SQL)
        this.$db.run(SQL, err => {
          if (err) {
            this.$message.warning('保存失败 er：' + err)
          } else {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.getSelfTableData()
          }
        })
      } else {
        if (this.view_info.editID > 0) {
          this.$message.warning('请先保存当前修改')
          return
        }
        this.view_info.sel = JSON.parse(JSON.stringify(row))
        row.isSet = true
        this.view_info.editID = row.id
        console.log('editID ' + row.id)
      }
    },
    delTableData (row) {
      console.log('delete ' + row.id)
      const SQL = `delete from zhuanli where id=` + row.id
      console.log(SQL)
      this.$db.run(SQL, err => {
        if (err) {
          this.$message.warning('删除失败 er：' + err)
        } else {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getSelfTableData()
        }
      })
    },
    getSelfTableData () {
      console.log('getSelfTableData')
      this.view_info.tabledata = []
      var sql = 'select * from zhuanli'
      this.$db.all(sql, (err, res) => {
        if (err) {
          this.$message.warning('获取数据失败 er：' + err)
        } else {
          // console.log(res)
          // console.log(res.length)
          for (var i = 0; i < res.length; i++) {
            console.log(res[i])
            res[i].isSet = false
            this.view_info.tabledata.push(res[i])
            this.tempDataTable.push(res[i])
            this.companyOptions.push(res[i].company)
          }
        }
      })
    },
    clearData () {
      this.view_info.sel = null
      this.view_info.editID = 0
      this.view_info.tabledata = []
      this.companyOption = ''
      this.companyOptions = []
      this.nameOption = ''
      this.tempDataTable = []
      this.getSelfTableData()
    },
    filterWithCompany (item) {
      let filteredData = []
      if (this.companyOption !== '') {
        for (let d of this.tempDataTable) {
          console.log(item, d)
          if (this.companyOption === d.company) {
            filteredData.push(d)
          }
        }
        this.view_info.tabledata = filteredData
      }
    }
  },
  created () {
    this.getSelfTableData()
  }
}
</script>
<style>
.condition{
  display:flex;
  flex-direction:row;
  
}
.action{
  display:flex;
  flex-direction:row;
  align-items: flex-start ;
}
.el-table-add-row {
    margin-top: 10px;
    width: 100%;
    height: 34px;
    border: 1px dashed #c1c1cd;
    border-radius: 3px;
    cursor: pointer;
    justify-content: center;
    display: flex;
    line-height: 34px;
}
.el-table .cell, .el-table th {
    height: 35px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    line-height: 15px;
    user-select: text;
}
</style>
